package com.westcom.vulb.activity;

import java.util.ArrayList;

import com.westcom.vulb.logic.SessionManager;
import com.westcom.vulb.logic.account;
import com.westcom.vulb.protocal.http.Response;

import android.app.Activity;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;

public abstract class CardInfoBasicFragment extends Fragment {
    public abstract void onCardDetailLoaded();
    public void onLogoLoaded(Integer uid, Bitmap logo) {
    }
    
    protected ProgressDialog mLoadingDialog;
    
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        if (mLoadingDialog == null) 
        {
            mLoadingDialog = new ProgressDialog(getActivity());
            mLoadingDialog.setMessage(getActivity().getResources().getString(R.string.loading));
        }
    }
    
    public CardInteractActivity selfActivity() {
        return (CardInteractActivity) getActivity();
    }
    
    protected Handler mLogoHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            int uid = msg.arg1;
            Bitmap logo = (Bitmap) msg.obj;
            
            onLogoLoaded(uid, logo);
            return true;
        }
    });
    
    protected LoadingLogo mLogoLoader;
    
    protected void loadLogo(ArrayList<Integer> uids) {
        if (uids == null || uids.size() <= 0) {
            return;
        }
        
        if (mLogoLoader == null) {
            mLogoLoader = new LoadingLogo();
        }
        mLogoLoader.execute(uids);
    }
    
    public class LoadingLogo extends AsyncTask<ArrayList<Integer>, Integer, Integer> 
    {
        @Override
        protected Integer doInBackground(ArrayList<Integer>... params) {
            ArrayList<Integer> uids = params[0];
            for (Integer uid : uids) 
            {
    			Response res = account.getInstanse().GetProfileImage(uid, "", 
    			        SessionManager.getInstance().getCurrentSession().getSessionid());
    			String bitmap_str = (String) res.data.get("personImg");
    			Bitmap logo = account.Base64Str2Bitmap(bitmap_str);
    			Message.obtain(mLogoHandler, 0, uid, 0, logo).sendToTarget();
            }
            
            return null;
        }

        @Override
        protected void onPostExecute(Integer result) {
            super.onPostExecute(result);
            
            mLoadingDialog.hide();
        }
    }
}